package jsp;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * Author:shixiaojun@itany.com
 * Date:2022/4/13 14:45
 * Version:1.0-SNAPSHOT
 * Description:
 */
@WebServlet("*.code")
public class CodeServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path = request.getServletPath();
        if("/show.code".equals(path)){
            showCode(request,response);
        }
    }

    public void showCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Random random = new Random();
        // 在内存中定义一个画板（图像缓冲区）
        BufferedImage image = new BufferedImage(50,25,BufferedImage.TYPE_INT_RGB);
        // 获取画板中的画笔,用于编辑图像缓冲区的内容
        Graphics graphics = image.getGraphics();
        // 设置画笔所编辑的区域大小
        graphics.fillRect(0,0,50,25);
        // 设置画笔的颜色,随机色
        graphics.setColor(new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256)));
        // 设置字体的样式
        graphics.setFont(new Font("宋体",Font.BOLD+Font.ITALIC,18));
        // 绘制验证码的内容
        // 假设随机四位英文字母或者数字
        // 准备一个字符串,这个字符串值的内容即为验证码中可能出现的数字或者英文字母
        // 通过方法获取该字符串随机索引位置的字符就能获取到随机的英文字母或者数字
        String s = "qwertyuiopasdfghjklzxcvbnm0123456789";
        StringBuffer buffer = new StringBuffer();
        for(int i = 0; i < 4; i++){
            buffer.append(s.charAt(random.nextInt(s.length())));
        }
        // 生成验证码的内容
        String code = buffer.toString();
        // 此时可以将验证码的内容保存到session,便于校验
        request.getSession().setAttribute("code",code);
        System.out.println("验证码:"+code);
        // 将随机数绘制到图片中
        graphics.drawString(code,5,18);
        // 使用ImageIO输出图片
        ImageIO.write(image,"JPEG",response.getOutputStream());
    }

}
